<!--
  系统仪表盘
  功能：系统概览，包含数据统计、快捷操作、系统信息等
-->
<template>
  <div class="dashboard">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-content">
        <h1 class="welcome-title">欢迎使用传奇管理系统</h1>
        <div class="welcome-subtitle">系统运营数据一目了然</div>
      </div>
      <div class="welcome-time">
        <div class="current-time">{{ currentTime }}</div>
        <div class="current-date">{{ currentDate }}</div>
      </div>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card" v-for="stat in statsData" :key="stat.key">
          <div class="stat-icon">
            <el-icon :size="32">
              <component :is="stat.icon" />
            </el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stat.value }}</div>
            <div class="stat-label">{{ stat.label }}</div>
          </div>
          <div class="stat-trend" :class="stat.trend">
            <el-icon><component :is="stat.trendIcon" /></el-icon>
            {{ stat.change }}%
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷操作区域 -->
    <div class="quick-actions">
      <div class="section-header">
        <h2>快捷操作</h2>
      </div>
      <div class="actions-grid">
        <div 
          class="action-card" 
          v-for="action in quickActions" 
          :key="action.key"
          @click="handleQuickAction(action)"
        >
          <div class="action-icon">
            <el-icon :size="24">
              <component :is="action.icon" />
            </el-icon>
          </div>
          <div class="action-title">{{ action.title }}</div>
          <div class="action-desc">{{ action.description }}</div>
        </div>
      </div>
    </div> 

    <!-- 系统信息区域 -->
    <div class="system-info">
      <div class="section-header">
        <h2>系统信息</h2>
        <el-button @click="handleRefreshSystemInfo">刷新</el-button>
      </div>
      <div class="info-grid">
        <div class="info-item" v-for="info in systemInfo" :key="info.key">
          <div class="info-label">{{ info.label }}</div>
          <div class="info-value">{{ info.value }}</div>
        </div>
      </div>
    </div>

    <!-- 最近活动 -->
    <div class="recent-activities">
      <div class="section-header">
        <h2>最近活动</h2>
        <el-button @click="handleViewAllActivities">查看全部</el-button>
      </div>
      <div class="activities-list">
        <div 
          class="activity-item" 
          v-for="activity in recentActivities" 
          :key="activity.id"
        >
          <div class="activity-avatar">
            <el-avatar 
              :size="40" 
              :src="activity.avatar || '/test.jpg'"
              @error="() => true"
            >
              {{ activity.user.charAt(0) }}
            </el-avatar>
          </div>
          <div class="activity-content">
            <div class="activity-text">
              <strong>{{ activity.user }}</strong>
              {{ activity.action }}
            </div>
            <div class="activity-time">{{ activity.time }}</div>
          </div>
          <div class="activity-icon">
            <el-icon><component :is="activity.icon" /></el-icon>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { 
  ref, 
  reactive, 
  computed,
  onBeforeMount,
  onMounted, 
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
  onErrorCaptured,
  nextTick 
} from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

// 组件名称
defineOptions({
  name: 'DashboardIndex'
})

// 路由
const router = useRouter()

// 响应式变量声明（按照模板中的顺序）
const currentTime = ref('')
const currentDate = ref('')
const timer = ref(null)

// 响应式对象
const statsData = reactive([
  {
    key: 'users',
    label: '总用户数',
    value: '1,234',
    icon: 'User',
    trend: 'up',
    trendIcon: 'ArrowUp',
    change: 12.5
  },
  {
    key: 'orders',
    label: '今日订单',
    value: '456',
    icon: 'Document',
    trend: 'up',
    trendIcon: 'ArrowUp',
    change: 8.2
  },
  {
    key: 'revenue',
    label: '今日收入',
    value: '¥8,888',
    icon: 'Money',
    trend: 'down',
    trendIcon: 'ArrowDown',
    change: 3.1
  },
  {
    key: 'visits',
    label: '访问量',
    value: '9,876',
    icon: 'View',
    trend: 'up',
    trendIcon: 'ArrowUp',
    change: 15.3
  }
])

const quickActions = reactive([
  {
    key: 'user',
    title: '用户管理',
    description: '管理系统用户',
    icon: 'User'
  },
  {
    key: 'role',
    title: '角色管理',
    description: '配置用户角色',
    icon: 'UserFilled'
  },
  {
    key: 'menu',
    title: '菜单管理',
    description: '配置系统菜单',
    icon: 'Menu'
  },
  {
    key: 'auth',
    title: '权限管理',
    description: '管理权限配置',
    icon: 'Key'
  }
])

const systemInfo = reactive([
  {
    key: 'version',
    label: '系统版本',
    value: 'v1.0.0'
  },
  {
    key: 'runtime',
    label: '运行时间',
    value: '7天 12小时'
  },
  {
    key: 'memory',
    label: '内存使用',
    value: '512MB / 2GB'
  },
  {
    key: 'cpu',
    label: 'CPU使用率',
    value: '25%'
  },
  {
    key: 'storage',
    label: '存储空间',
    value: '15GB / 100GB'
  },
  {
    key: 'database',
    label: '数据库',
    value: 'MySQL 8.0'
  }
])

const recentActivities = reactive([
  {
    id: 1,
    user: '管理员',
    action: '创建了新的用户账号',
    time: '2分钟前',
    icon: 'User',
    avatar: '/test.jpg'
  },
  {
    id: 2,
    user: '张三',
    action: '修改了角色权限',
    time: '15分钟前',
    icon: 'UserFilled',
    avatar: '/test.jpg'
  },
  {
    id: 3,
    user: '李四',
    action: '添加了新菜单',
    time: '1小时前',
    icon: 'Menu',
    avatar: '/test.jpg'
  },
  {
    id: 4,
    user: '王五',
    action: '更新了系统配置',
    time: '3小时前',
    icon: 'Setting',
    avatar: '/test.jpg'
  }
])

// 常量定义
const UPDATE_INTERVAL = 1000 // 更新时间间隔（毫秒）

// 计算属性
const formattedDate = computed(() => {
  const now = new Date()
  const options = { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric', 
    weekday: 'long' 
  }
  return now.toLocaleDateString('zh-CN', options)
})

// 响应函数声明（按照模板中的顺序）
/**
 * 更新当前时间
 */
const updateTime = () => {
  const now = new Date()
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  currentTime.value = `${hours}:${minutes}:${seconds}`
  currentDate.value = formattedDate.value
}

/**
 * 快捷操作处理
 */
const handleQuickAction = (action) => {
  const routeMap = {
    user: '/system/user',
    role: '/system/role',
    menu: '/system/menu',
    auth: '/system/auth'
  }
  
  if (routeMap[action.key]) {
    router.push(routeMap[action.key])
    ElMessage.success(`跳转到${action.title}`)
  }
}

/**
 * 刷新系统信息
 */
const handleRefreshSystemInfo = () => {
  // 模拟刷新操作
  ElMessage.success('系统信息已刷新')
  
  // 更新运行时间
  systemInfo[1].value = '7天 12小时 30分钟'
}

/**
 * 查看所有活动
 */
const handleViewAllActivities = () => {
  ElMessage.info('活动记录功能开发中')
}

// 样式函数声明
/**
 * 启动定时器
 */
const startTimer = () => {
  updateTime()
  timer.value = setInterval(updateTime, UPDATE_INTERVAL)
}

/**
 * 清理定时器
 */
const clearTimer = () => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
}

/**
 * 初始化数据
 */
const initData = () => {
  // 可以在这里从API获取真实数据
  console.log('初始化仪表盘数据')
}

// 生命周期钩子
onBeforeMount(() => {
  // 组件挂载前执行的逻辑
  initData()
})

onMounted(() => {
  // 组件挂载后执行的逻辑
  startTimer()
})

onBeforeUpdate(() => {
  // 组件更新之前执行的逻辑
  nextTick(() => {
    // 在DOM更新之后执行的逻辑
  })
})

onUpdated(() => {
  // 组件更新之后执行的逻辑
})

onBeforeUnmount(() => {
  // 组件卸载前执行的逻辑
  clearTimer()
})

onUnmounted(() => {
  // 组件卸载后执行的逻辑
})

onErrorCaptured((err, instance, info) => {
  // 捕获来自后代组件的错误
  console.error('仪表盘组件错误:', err, info)
  return false // 阻止错误继续向上传播
})
</script>

<style lang="less" scoped>
.dashboard {
  // 欢迎区域
  .welcome-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    padding: 30px;
    border-radius: 12px;
    margin-bottom: 24px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);

    .welcome-content {
      .welcome-title {
        margin: 0 0 8px 0;
        font-size: 28px;
        font-weight: 600;
      }

      .welcome-subtitle {
        font-size: 16px;
        opacity: 0.9;
      }
    }

    .welcome-time {
      text-align: right;

      .current-time {
        font-size: 24px;
        font-weight: 600;
        margin-bottom: 4px;
      }

      .current-date {
        font-size: 14px;
        opacity: 0.9;
      }
    }
  }

  // 数据统计区域
  .stats-section {
    margin-bottom: 24px;

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      gap: 20px;

      .stat-card {
        background: #fff;
        padding: 24px;
        border-radius: 12px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        display: flex;
        align-items: center;
        position: relative;

        .stat-icon {
          width: 60px;
          height: 60px;
          background: linear-gradient(135deg, #409EFF 0%, #66b3ff 100%);
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
          margin-right: 16px;
        }

        .stat-content {
          flex: 1;

          .stat-value {
            font-size: 28px;
            font-weight: 600;
            color: #333;
            margin-bottom: 4px;
          }

          .stat-label {
            color: #666;
            font-size: 14px;
          }
        }

        .stat-trend {
          display: flex;
          align-items: center;
          font-size: 14px;
          font-weight: 500;

          &.up {
            color: #67c23a;
          }

          &.down {
            color: #f56c6c;
          }

          .el-icon {
            margin-right: 4px;
          }
        }
      }
    }
  }

  // 快捷操作区域
  .quick-actions {
    margin-bottom: 24px;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #333;
      }
    }

    .actions-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
      gap: 16px;

      .action-card {
        background: #fff;
        padding: 20px;
        border-radius: 12px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
        text-align: center;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-4px);
          box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);

          .action-icon {
            background: #409EFF;
            color: #fff;
          }
        }

        .action-icon {
          width: 48px;
          height: 48px;
          background: #f0f2f5;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin: 0 auto 12px;
          color: #666;
          transition: all 0.3s ease;
        }

        .action-title {
          font-size: 16px;
          font-weight: 600;
          color: #333;
          margin-bottom: 4px;
        }

        .action-desc {
          font-size: 12px;
          color: #999;
        }
      }
    }
  }

  // 系统信息区域
  .system-info {
    margin-bottom: 24px;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #333;
      }
    }

    .info-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 16px;

      .info-item {
        background: #fff;
        padding: 16px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

        .info-label {
          font-size: 14px;
          color: #666;
          margin-bottom: 8px;
        }

        .info-value {
          font-size: 16px;
          font-weight: 600;
          color: #333;
        }
      }
    }
  }

  // 最近活动
  .recent-activities {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #333;
      }
    }

    .activities-list {
      background: #fff;
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

      .activity-item {
        display: flex;
        align-items: center;
        padding: 16px 20px;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .activity-avatar {
          margin-right: 12px;
        }

        .activity-content {
          flex: 1;

          .activity-text {
            font-size: 14px;
            color: #333;
            margin-bottom: 4px;

            strong {
              color: #409EFF;
            }
          }

          .activity-time {
            font-size: 12px;
            color: #999;
          }
        }

        .activity-icon {
          color: #409EFF;
          font-size: 18px;
        }
      }
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    .welcome-section {
      flex-direction: column;
      text-align: center;

      .welcome-time {
        text-align: center;
        margin-top: 16px;
      }
    }

    .stats-grid {
      grid-template-columns: 1fr;
    }

    .actions-grid {
      grid-template-columns: 1fr;
    }

    .info-grid {
      grid-template-columns: 1fr;
    }
  }
}
</style>